const fs = require('fs')
const XLSX = require('xlsx')
const { workArea } = require('./config.js');
process.on('message', (msg) => {
    const folder = `upload-tool(node)/static/${msg.fileName.split('.')[0]}`
    fs.mkdirSync(`../${folder}/数据整理/汇总`, { recursive: true })
    const userFolder = fs.readdirSync(`../${folder}/数据整理`);
    let SheetData = []
    let PoData = []
    let DwData = []
    let SheetData2 = []
    let PoData2 = []
    let DwData2 = []
    userFolder.map((item, i) => {
        process.send({ all: userFolder.length, current: i || 1, progress: true })//将进度传给封装的命令文件
        if (i === folder.length - 1) return undefined
        console.log(`${item}文件汇总中---${i + 1}/${userFolder.length}`);
        let file = null
        try {
            const allFilter = fs.readdirSync(`../${folder}/数据整理/${item}`);
            const filterName = allFilter.find(v => v.includes('汇总'))
            file = XLSX.readFile(`../${folder}/数据整理/${item}/${filterName}`)
        } catch (e) {
            console.log(`${item}没有汇总文件`);
            return undefined
        }
        workArea.map((v, idx) => {
            v.map((val) => {
                const worksheet = file.Sheets[val];
                if (!worksheet) return undefined
                const data = XLSX.utils.sheet_to_json(worksheet, {
                    defval: "" // 空单元格返回空字符串，而不是 undefined
                });
                data.forEach((v) => {
                    const A1 = Object.keys(v)[0]
                    const B1 = Object.keys(v)[1]
                    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
                    if (idCardRegex.test(v[B1])) {
                        if (idx == 0) {
                            SheetData.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                        if (idx == 1) {
                            PoData.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                        if (idx == 2) {
                            DwData.push({ '名字': v[A1], '身份证号': v[B1] })
                        }
                    }
                })
            })
        })
        // let file2 = null
        // try {
        //     file2 = XLSX.readFile(`../${folder}/数据整理/${item}/接收方/接收方数据统计.xlsx`)
        // } catch (e) {
        //     console.log(`${item}没有接收方`);
        //     return undefined
        // }
        // workArea.map((v, idx) => {
        //     v.map((val) => {
        //         const worksheet = file2.Sheets[val];
        //         if (!worksheet) return undefined
        //         const data = XLSX.utils.sheet_to_json(worksheet, {
        //             defval: "" // 空单元格返回空字符串，而不是 undefined
        //         });
        //         data.forEach((v) => {
        //             const A1 = Object.keys(v)[0]
        //             const B1 = Object.keys(v)[1]
        //             const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/
        //             if (idCardRegex.test(v[B1])) {
        //                 if (idx == 0) {
        //                     SheetData.push({ '名字': v[A1], '身份证号': v[B1] })
        //                 }
        //                 if (idx == 1) {
        //                     PoData.push({ '名字': v[A1], '身份证号': v[B1] })
        //                 }
        //                 if (idx == 2) {
        //                     DwData.push({ '名字': v[A1], '身份证号': v[B1] })
        //                 }
        //             }
        //         })
        //     })
        // })
    })
    // 添加工作表并创建文件
    const workbook = XLSX.utils.book_new();
    const toplimit = 1048575
    if (SheetData.length < toplimit) {
        SheetData = Array.from(new Map(SheetData.map(item => [item['身份证号'], item])).values());
        const Sheet = XLSX.utils.json_to_sheet(SheetData);
        XLSX.utils.book_append_sheet(workbook, Sheet, workArea[0][0]);
        XLSX.writeFile(workbook, `../${folder}/数据整理/汇总/汇总-${SheetData.length}条数据.xlsx`);
    } else {
        let result = []
        SheetData = Array.from(new Map(SheetData.map(item => [item['身份证号'], item])).values());
        for (let i = 0; i < SheetData.length; i += toplimit) {
            result.push(SheetData.slice(i, i + toplimit));
        }
        SheetData = []
        for (let sheetIndex = 0; sheetIndex < result.length; sheetIndex++) {
            const Sheet = XLSX.utils.json_to_sheet(result[sheetIndex]);
            XLSX.utils.book_append_sheet(workbook, Sheet, workArea[0][0] + (sheetIndex + 1));
        }
        XLSX.writeFile(workbook, `../${folder}/数据整理/汇总/汇总-${SheetData.length}条数据.xlsx`);
    }
    if (PoData.length) {
        PoData = Array.from(new Map(PoData.map(item => [item['身份证号'], item])).values());
        const PO = XLSX.utils.json_to_sheet(PoData);
        XLSX.utils.book_append_sheet(workbook, PO, workArea[1][0]);
        XLSX.writeFile(workbook, `../${folder}/数据整理/汇总/汇总-${SheetData.length}条数据.xlsx`);
    }
    if (DwData.length) {
        DwData = Array.from(new Map(DwData.map(item => [item['身份证号'], item])).values());
        const DW = XLSX.utils.json_to_sheet(DwData);
        XLSX.utils.book_append_sheet(workbook, DW, workArea[2][0]);
        XLSX.writeFile(workbook, `../${folder}/数据整理/汇总/汇总-${SheetData.length}条数据.xlsx`);
    }

    // const workbook2 = XLSX.utils.book_new();
    // if (SheetData2.length) {
    //     SheetData2 = Array.from(new Map(SheetData2.map(item => [item['身份证号'], item])).values());
    //     const Sheet2 = XLSX.utils.json_to_sheet(SheetData2);
    //     XLSX.utils.book_append_sheet(workbook2, Sheet2, workArea[0][0]);
    // }
    // if (PoData2.length) {
    //     PoData2 = Array.from(new Map(PoData2.map(item => [item['身份证号'], item])).values());
    //     const PO2 = XLSX.utils.json_to_sheet(PoData2);
    //     XLSX.utils.book_append_sheet(workbook2, PO2, workArea[1][0]);
    // }
    // if (DwData2.length) {
    //     DwData2 = Array.from(new Map(DwData2.map(item => [item['身份证号'], item])).values());
    //     const DW2 = XLSX.utils.json_to_sheet(DwData2);
    //     XLSX.utils.book_append_sheet(workbook2, DW2, workArea[2][0]);
    // }
    // XLSX.writeFile(workbook2, `../${folder}/数据整理/汇总/接收方数据统计.xlsx`);
    console.log(`总文件汇总完成`);
    process.send({ progress: false })//将进度传给主进程
})

